package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    // 自创类不能spring自动注入，通过调用处的自动注入的stringRedisTemplate来完成拦截器的带参构造，并传入注入的StringredisTemplate

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、获取token
        String token = request.getHeader("authorization");
//        System.out.println(token);

        // 此处通过StrUtil工具类来进行处理token为空，因为“”并不是null，因此不能通过判null
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // 2、从redis中获取userMap
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
//        System.out.println(userMap);

        // 3、判断user是否存在不存在则拦截
        if (userMap.isEmpty()) {
            return true;
        }
        // 4、将userMap转为userDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        // 5、存在保存在Threadlocal
        UserHolder.saveUser(userDTO);
        // 6、刷新token的有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
        // 7、放行
        return true;
    }
}
